package com.ws.base.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

import com.ws.base.common.WSAppLogger;

public class CRC32Util {
    private CRC32Util() {
    }

    private static class SingletonHolder {
        private final static CRC32Util INSTANCE = new CRC32Util();
    }

    public static CRC32Util getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private WSAppLogger log = WSAppLogger.getWSAppLogger(CRC32Util.class);

    public String getFileCRC32(File file) {
        String crc32 = null;
        CheckedInputStream cis = null;
        FileInputStream in = null;

        try {
            in = new FileInputStream(file);
            cis = new CheckedInputStream(in, new CRC32());
            byte[] buf = new byte[10240];
            while (cis.read(buf) >= 0) {
            }
            long val = cis.getChecksum().getValue();
            crc32 = Long.toHexString(val);
        } catch (IOException e) {
            log.error(e);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e, "close stream error");
                }
            }
        }

        return crc32;
    }
}
